﻿using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace TaskProject
{
    public class MyTask : IAsyncResult,IDisposable
    {
        public object AsyncState => throw new NotImplementedException();

        public WaitHandle AsyncWaitHandle => throw new NotImplementedException();

        public bool CompletedSynchronously => throw new NotImplementedException();

        public bool IsCompleted => throw new NotImplementedException();

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }


    /// <summary>
    /// 主要用来搞定TASK这个任务
    /// </summary>
    class Program
    {
        static CancellationTokenSource ct = new CancellationTokenSource();


        static void Main(string[] args)
        {
            WriteStars();
            var task1 = Task.Run(() => DoWork(ct.Token), ct.Token);
            //var task2 = Task.Run(() => DoWork(ct.Token), ct.Token);
            //task.ContinueWith(task => Console.WriteLine("I AM IS Completed"),TaskContinuationOptions.OnlyOnRanToCompletion);
            //task1.ContinueWith(t => Console.WriteLine(" I AN IS FALUD"),TaskContinuationOptions.OnlyOnFaulted);
            Console.Read();
            ct.Cancel();
            #region 通过AggregateException 异常集合处理异常

            //try
            //{
            //    Task.WaitAll(task2,task1);
            //}
            //catch (AggregateException ex)
            //{
            //    ex.Handle(ex =>
            //    {
            //        Console.WriteLine($"发生了错误！{ex.Message}");
            //        return true;
            //    });
            //    Console.WriteLine(ex.Message);
            //}
            #endregion
            WriteStars();
            Console.WriteLine(task1.Status);
            Console.ReadKey();

        }

        private static void WriteStars()
        {

            Console.WriteLine("*".PadLeft(Console.WindowWidth - 1, '*'));
        }


        private static void DoWork(CancellationToken cts)
        {
            throw new Exception("i am error!");
            var range = Enumerable.Range(0, 10000).ToArray();
            for (int i = 0; i < range.Count(); i++)
            {
                if (!cts.IsCancellationRequested)
                {
                    Task.Delay(2000).Wait();
                    Console.Write(range[i] + "  ");
                }
            }
        }
    }
}
